package org.koin.test;

import org.junit.rules.TestWatcher;
import org.junit.runner.Description;
import org.koin.core.Koin;
import org.koin.core.context.DefaultContextExt;
import org.koin.dsl.KoinAppDeclaration;

public class KoinTestRule extends TestWatcher {
    private KoinAppDeclaration appDeclaration;

    private Koin _koin = null;

    private KoinTestRule(KoinAppDeclaration appDeclaration) {
        this.appDeclaration = appDeclaration;
    }

    public static KoinTestRule create(KoinAppDeclaration appDeclaration) {
        return new KoinTestRule(appDeclaration);
    }

    public Koin getKoin() {
        Koin koin = this._koin;
        if (koin != null) {
            return koin;
        } else {
            throw new IllegalStateException("No Koin application found");
        }
    }

    @Override
    protected void starting(Description description) {
        super.starting(description);
        try {
            this._koin = DefaultContextExt.startKoin(this.appDeclaration).getKoin();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void finished(Description description) {
        super.finished(description);
        DefaultContextExt.stopKoin();
        this._koin = null;
    }
}
